package com.tmxk.api.days01.yangl.list;

import com.tmxk.api.days01.yangl.Dog;

import java.util.ArrayList;

/**
 * @BelongsProject: java-api
 * @BelongsPackage: com.tmxk.api.days01.yangl
 * @Author: YangLei
 * @CreateTime: 2022-11-28  13:58
 * @Description: TODO
 * @Version: 1.0
 */
public class ArrayListDemo3_Generic {
    public static void main(String[] args) {
        ArrayList<Dog> arrayList = new ArrayList<>();
        Dog dog1 = new Dog("小花", 2);
        arrayList.add(dog1);
        arrayList.add(dog1);
        arrayList.add(new Dog("花花", 3));
        arrayList.add(new Dog("小黑", 1));
        arrayList.add(new Dog("小白", 5));
        arrayList.add(new Dog("汪汪", 6));
        arrayList.add(dog1);

        System.out.println("\n循环遍历该集合元素");
        for (int i = 0; i < arrayList.size(); i++) {
            System.out.println(arrayList.get(i));
        }

        //获取第三个下标元素的狗狗对象
        Dog dog = arrayList.get(2);
        System.out.println("获取第三个下标元素的狗狗对象:" + dog);

        //查找是否存在汪汪这个集合元素
        boolean isFind = false;
        for (int i = 0; i < arrayList.size(); i++) {
            Dog d = arrayList.get(i);
            if ("汪汪".equals(d.getName())) {
                //isFind = arrayList.contains(d);
                isFind = true;
                break;
            }
        }
        System.out.println(isFind == true ? "存在该元素" : "不存在该元素");

        //删除花花
        //定义一个标识符，用来标识是否成功删除该集合元素，默认定义false，未删除成功
        boolean isRemove = false;
        for (int i = 0; i < arrayList.size(); i++) {
            Dog d = arrayList.get(i);
            if ("花花".equals((d.getName()))) {
                isRemove = arrayList.remove(d);
            }
        }
        System.out.println(isRemove == true ? "删除花花成功" : "删除花花失败");

        //arrayList.remove(1);

        //循环遍历该集合元素
        System.out.println("\n循环遍历该集合元素");
        for (int i = 0; i < arrayList.size(); i++) {
            System.out.println(arrayList.get(i).getName() + "\t" + arrayList.get(i).getAge());
        }

        // 操作集合元素时出现 java.lang.ClassCastException 该异常情况时, 使用 泛型 即可解决;
    }
}
